package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author:SA
 * @DATA:DATA
 * 德鲁伊连接池工具类
 */


public final class DruidUtil{
    private DruidUtil(){}
    private static DataSource dataSource = null;
    //初始化资源 读取配置文件
    static {

//        ResourceBundle druid = ResourceBundle.getBundle("druid");
//        String driver = druid.getString("driver");
//        System.out.println("driver = " + driver);

        try {
            Properties properties = new Properties();
            //通过类加载器加载配置文件
            InputStream in = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取数据库连接池
    public static DataSource getDataSource(){
        return dataSource;
    }

    //获取连接
    public static Connection getConnection(){
        //通过数据库连接池获取连接
        Connection connection = null;
        try {
            if(dataSource!=null){
                connection = dataSource.getConnection();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //释放资源的方法
    public static void closeAll(ResultSet rs, Statement statement,Connection connection){
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(statement!=null){
                statement.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Connection connection = DruidUtil.getConnection();
        System.out.println("connection = " + connection);

    }


}
